package com.example.demo.utils;


import com.example.demo.constent.RequestContext;
import com.example.demo.mapper.UserDao;
import com.example.demo.entity.UserEntity;
import com.example.demo.exception.BusinessException;
import com.example.demo.exception.RespCode;
import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.util.Optional;


/**
 * @author wumin
 * @version 1.0
 * @Description: 登录工具类
 * @date 2021/6/2 15:16
 */
@Component
@Slf4j
public class LoginUtil {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDao userDao;


    public UserEntity getLogin() {
        String userId = getTokenUserId();
        String token = redisUtil.get("token:"+userId);
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(RespCode.REGISTER_ERROR_TOKEN_EXIT.getName());
        }

        UserEntity userEntity = userDao.selectById(userId);

        return userEntity;
    }

    public Optional<String> getToken() {
        HttpServletRequest request = RequestContext.getCurrentRequest();
        if (request != null) {
            return getTokenFromHeader(request);
        }
        return Optional.empty();
    }

    private Optional<String> getTokenFromHeader(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && !header.isEmpty()) {
            //去掉前缀
//            if (header.startsWith("")) {
//                return Optional.of(header.substring("".length()));
//            }
            return Optional.ofNullable(header);
        }
        return Optional.empty();
    }

    public Boolean logout() {
        String userId = getTokenUserId();
        return redisUtil.delete("token:"+userId);
    }

    private String getTokenUserId() {
        String authorization = getToken().get();
        if (StringUtils.isEmpty(authorization)) {
            throw new BusinessException(RespCode.REGISTER_ERROR_TOKEN_EXIT.getName());
        }
        String userId = jwtUtils.getUserId(authorization);
        if(StringUtils.isEmpty(userId)){
            throw new BusinessException(RespCode.REGISTER_ERROR_TOKEN.getName());
        }
        return userId;
    }
}
